var express = require('express');
const mysqlExec = require('../db/dbMysql.js');
const {
  Msg,
  curPath,
  creatJWT,
  useJWT
} = require('../tools/msg.js');
const md5 = require('md5'); //md5加密字符串
const fs=require('fs');
const path=require('path');
const formidable=require('formidable');
const {
  v4: uuidv4
} = require('uuid'); //生成唯一字符串
var svgCaptcha = require('svg-captcha');
var router = express.Router();

//处理用户更换头像
router.post('/uploadimg',async(req,res)=>{
  let jwtdata=req.headers.authorization ? req.headers.authorization : '';
  if(!jwtdata){
    res.send(Msg(500,'非法访问，请先登录'));
    return;
  }
  let obj=useJWT(jwtdata);
  if(!obj){
    res.send(Msg(500,'非法访问，请先登录'));
    return;
  }
  let uploadPath=path.join(__dirname,'../uploads/avatar');
  //上传后存放的位置
  const form=formidable({multiples:true,uploadDir:uploadPath});
  form.parse(req,async(err,fields,files)=>{
    console.log(fields,files);
    if(err){
      res.send(Msg(500,'文件上传失败'));
    }else{
      //获取文件扩展名
      let nameArr=files.logo.originalFilename.split('.');
      let extName=nameArr[nameArr.length-1];
      //完整的文件名
      let fullname=`${files.logo.newFilename}.${extName}`;
      fs.renameSync(files.logo.filepath,`${uploadPath}/${fullname}`);
      //修改用户表中当前用户的头像信息：
      let sql=`update e_member set head_photo_url='${fullname}'`;
      let [err,obj2]=await mysqlExec(sql);
      if(err){
        res.send(Msg(200,'文件上传成功',{ filePath: `${curPath}avatar/${fullname}` }));
      }else{
        res.send(Msg(500,'文件上传失败'));
      }
    }
  })
})

//修改账户数据
router.post('/modifyinfos',async(req,res)=>{
  let{jwtdata='',realname='',sex='',birthdate='',city=''}=req.body;
  if(!jwtdata){
    res.send(Msg(500,'非法访问，请先登录'));
    return;
  }
  let obj=useJWT(jwtdata);
  if(!obj){
    res.send(Msg(500,'非法访问，请先登录'));
    return;
  }
  let sql=`update e_member set realname='${realname}',sex='${sex}',birthdate='${birthdate}',city='${city}' where mid='${obj.uid}'`;
  let [err,obj2]=await mysqlExec(sql);
  console.log(err);
  if(err){
    if(obj2.affectedRows==1){
      res.send(Msg(200,'账户数据修改成功'));
    }else{
      res.send(Msg(500,'账户数据修改失败了'));
    }
  }else{
    res.send(Msg(500,'账户数据修改失败'));
  }
})

//我的账户数据：
router.post('/userinfos',async(req,res)=>{
  let{jwtdata=''}=req.body;
  if(jwtdata==''){
    res.send(Msg(500,'非法访问，请先登录'));
    return;
  }
  let obj=useJWT(jwtdata);
  if(!obj){
    res.send(Msg(500,'非法访问，请先登录'));
    return;
  }

  //根据已登录的用户id查询用户信息
  let sql=`select mid,realname,username,sex,birthdate,city,head_photo_url from e_member where mid='${obj.uid}'`;
  let [err,arr]=await mysqlExec(sql);
  if(err){
    res.send(Msg(200,'我的账户数据查询成功',arr));
  }else{
    res.send(Msg(500,'我的账户数据查询失败'));
  }
})

//我的课程
router.post('/mycourse',async(req,res)=>{
  let{jwtdata=''}=req.body;
  if(!jwtdata){
    res.send(Msg(500,'非法访问，请先登录'));
    return;
  }
  let obj=useJWT(jwtdata);
  if(!obj){
    res.send(Msg(500,'非法访问，请先登录'));
  }
  //查询我的课程信息
  let sql=`select o.cid,title,concat('${curPath}course/',image_src) as image_src,area_name,subject_name from e_order as o left join e_course as c on o.cid=c.cid  where mid='${obj.uid}'`;
  let [err,arr] = await mysqlExec(sql);
  if(err){
    res.send(Msg(200,'我的课程查询成功',arr));
  }else{
    res.send(Msg(500,'我的课程查询失败'));
  }
})
/* GET users listing. */
router.get('/syscode', function (req, res, next) {
  var captcha = svgCaptcha.create({
    size: 4,
    ignoreChars: '0oli',
    height: 40,
    width: 130
  });
  res.send(Msg(200, '验证码创建成功', {
    imgcode: captcha.data,
    codes: captcha.text
  }))
});

//用户登录接口
router.post('/login', async (req, res) => {
  let {
    uname = '', pwd = '', ucode = '', syscodes = ''
  } = req.body;
  if (!uname || !pwd || !ucode) {
    res.send(Msg(500, '账号及密码、验证码都不能为空'));
    return;
  }
  if (ucode.toUpperCase() != syscodes.toUpperCase()) {
    res.send(Msg(500, '验证码不正确'));
    return;
  }

  //先查询用户是否存在
  let sql = `select password,mid from e_member where username='${uname}'`;
  let [err,arr]=await mysqlExec(sql);
  if(err){
    if(arr.length==1){
      if(md5(pwd)==arr[0].password){
        let jwtData=creatJWT(arr[0].mid,uname);
        res.send(Msg(200,'登录成功',{jwtData}));
      }else{
        res.send(Msg(500,'密码错误'));
      }
    }else{
      res.send(Msg(500,'账号不存在'));
    }
  }else{
    res.send(Msg(500,'账号查询失败'));
  }
})

//用户注册接口
router.post('/register',async(req,res)=>{
  let {uname='',pwd='',repwd='', ucode = '', syscodes = ''}=req.body;
  if(!uname||!pwd||!repwd){
    res.send(Msg(500,'账号密码及确认密码都不能为空'));
    return;
  }

  if (ucode.toUpperCase() != syscodes.toUpperCase()) {
    res.send(Msg(500, '验证码不正确'));
    return;
  }

  if(pwd!=repwd){
    res.send(Msg(500,'两次密码不一致'));
    return;
  }

  //查询用户是否注册过
  let sql=`select count(id) as n from e_member where username='${uname}'`;
  let [e,arr]=await mysqlExec(sql);
  if(e){
    if(arr[0].n==1){
      res.send(Msg(500,'用户已注册'));
      return;
    }
  }else{
    res.send(Msg(500,'查询失败'));
    return;
  }

  sql=`insert into e_member(mid,username,password,createdate)value('${uuidv4()}','${uname}','${md5(pwd)}','${new Date().getTime()}')`;
  let [err,datas]=await mysqlExec(sql);
  if(err){
    if(datas.affectedRows==1){
      res.send(Msg(200,'注册成功'));
    }else{
      res.send(Msg(500,'用户注册失败'));
    }
  }else{
    res.send(Msg(500,'用户注册失败'));
  }
});
module.exports = router;